package com.jfinal.weixin.api;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 封装微信api返回结果, 输出实体类
 * <p/>
 * 参考自 mpsdk4j
 */
@Slf4j
public class ApiResult {

    private static Prop _errorConfig;

    static {
        _errorConfig = PropKit.use("error_code.properties");
    }

    private Map<String, Object> map;
    private String json;
    private Integer errCode;
    private String errMsg;
    private String errCNMsg;

    /**
     * 构建ApiResult对象
     *
     * @param json
     */
    public ApiResult(String json) {
        try {
            this.json = json;
            this.map = JSON.parseObject(json, Map.class);
            this.errCode = (Integer) this.map.get("errcode");
            this.errMsg = (String) this.map.get("errmsg");

            this.errCNMsg = this.errCode == null ? "请求成功." : _errorConfig.get(String.valueOf(this.errCode));

            log.debug("WeChat api result: {}", json);
            if (this.getErrCode() != null && this.getErrCode() != 0) {
                log.error("WeChat api error: {}", this.getErrCNMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public ApiResult(Integer errCode, String errMsg, String errCNMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
        this.errCNMsg = errCNMsg;
    }

    /**
     * 创建默认返回
     *
     * @return
     */
    public static ApiResult createDefault() {
        return new ApiResult(-2, "api request exception.", "API请求异常.");
    }

    public static ApiResult create(String json) {
        return new ApiResult(json);
    }

    public Map<String, Object> getMap() {
        return map;
    }

    public String getJson() {
        return json;
    }

    public Integer getErrCode() {
        return this.errCode;
    }

    public String getErrMsg() {
        return this.errMsg == null ? "Unknown Error!" : this.errMsg;
    }

    public String getErrCNMsg() {
        return this.errCNMsg == null ? "未知错误!" : this.errCNMsg;
    }

    public boolean isSuccessful() {
        return (this.errCode == null || this.errCode.intValue() == 0);
    }

    public String toJSON() {
        return JSON.toJSONString(this);
    }

}
